﻿using System;
using System.ComponentModel;

namespace HSS.ComponentModel
{
	/// <summary>
	/// A Generic Type Converter to/from a string.
	/// </summary>
	/// <typeparam name="T">The type being convertered.</typeparam>
	public class GenericTypeConverter<T> : TypeConverter
	{
		/// <summary>
		/// Determines if the provided sourceType can be converted to a string.
		/// </summary>
		/// <param name="context">The <see cref="ITypeDescriptorContext"/>.</param>
		/// <param name="sourceType">The <see cref="Type"/> to evaluate.</param>
		/// <returns></returns>
		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
		{
			if (sourceType == typeof(string))
				return true;
			return base.CanConvertFrom(context, sourceType);
		}
		/// <summary>
		/// Convert a string that represents a generic type back into it's formal Type.
		/// </summary>
		/// <param name="context">The <see cref="ITypeDescriptorContext"/>.</param>
		/// <param name="culture">The requested <see cref="System.Globalization.CultureInfo"/> culture.</param>
		/// <param name="value">The string containing the type definition to convert.</param>
		/// <returns>The converted type.</returns>
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
		public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
		{
			if (value is string)
				return (T)Enum.Parse(typeof(T), (string)value, false);
			return base.ConvertFrom(context, culture, value);
		}
	}
}